package cn.bluethink.timescaledb.util;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.DefaultIdStrategy;
import io.protostuff.runtime.Delegate;
import io.protostuff.runtime.RuntimeEnv;
import io.protostuff.runtime.RuntimeSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.objenesis.Objenesis;
import org.springframework.objenesis.ObjenesisStd;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 使用Protostuff进行序列化和反序列化
 */
public class SerializableUtil {

    private static Logger logger = LoggerFactory.getLogger(SerializableUtil.class);

    private static Objenesis objenesis = new ObjenesisStd(true);

    //时间戳转换Delegate，解决时间戳转换后错误问题
    private final static Delegate<Timestamp> TIMESTAMP_DELEGATE = new TimestampDelegate();

    private final static DefaultIdStrategy idStrategy = ((DefaultIdStrategy) RuntimeEnv.ID_STRATEGY);

    private final static ConcurrentHashMap<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>();

    static {
        idStrategy.registerDelegate(TIMESTAMP_DELEGATE);
    }

    @SuppressWarnings("unchecked")
    private static <T> Schema<T> getSchema(Class<T> clazz) {
        Schema<T> schema = (Schema<T>) cachedSchema.get(clazz);
        if (schema == null) {
            schema = RuntimeSchema.getSchema(clazz);
            if (schema != null) {
                cachedSchema.put(clazz, schema);
            }
        }
        return schema;
    }

    /**
     * 序列化
     *
     * @param obj 序列化对象
     * @return 序列化后的byte[]值
     */
  /*  @SuppressWarnings("unchecked")
    public static <T> byte[] serializer(T obj) {
        Class<T> clazz = (Class<T>) obj.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);
        try {
            Schema<T> schema = getSchema(clazz);
            return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            logger.error(e.getClass() + ";" + e.getMessage());
            throw new IllegalStateException(e.getMessage(), e);
        } finally {
            buffer.clear();
        }
    }*/

    /**
     * 反序列化
     *
     * @return 返回的对象
     */
    /*public static <T> T deserializer(byte[] data, Class<T> clazz) {
        try {
            T obj = clazz.newInstance();
            Schema<T> schema = getSchema(clazz);
            ProtostuffIOUtil.mergeFrom(data, obj, schema);
            return obj;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new IllegalStateException(e.getClass() + ";" + e.getMessage(), e);
        }
    }*/
    @SuppressWarnings("unchecked")
    public static <T> byte[] serializer(T obj) {
        if (obj == null) {
            return null;
        }
        Class<T> cls = (Class<T>) obj.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            Schema<T> schema = getSchema(cls);
            byte[] bytes = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
            return bytes;
        } catch (Exception e) {
            logger.error(e.getClass().getName() + ";" + e.getMessage());
            throw new IllegalStateException(e.getMessage(), e);
        } finally {
            buffer.clear();
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T deserializer(byte[] bytes, Class<T> clazz) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        try {
            Schema<T> schema = getSchema(clazz);
            T obj = clazz.newInstance();
            //改为由Schema来实例化解码对象，没有构造函数也没有问题
            //T message = schema.newMessage();
            ProtostuffIOUtil.mergeFrom(bytes, obj, schema);
            return obj;
        } catch (Exception e) {
            logger.error(e.getClass().getName() + ";" + e.getMessage());
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> String serializeToString(T obj) {
        Class<T> cls = (Class<T>) obj.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            Schema<T> schema = getSchema(cls);
            return new String(ProtostuffIOUtil.toByteArray(obj, schema, buffer), "UTF-8");
        } catch (Exception e) {
            logger.error(e.getClass().getName() + ";" + e.getMessage());
            throw new IllegalStateException(e.getMessage(), e);
        } finally {
            buffer.clear();
        }
    }

    public static <T> T deserializeFromString(String data, Class<T> clazz) {
        try {
            T message = (T) objenesis.newInstance(clazz);
            Schema<T> schema = getSchema(clazz);
            ProtostuffIOUtil.mergeFrom(data.getBytes("UTF-8"), message, schema);
            return message;
        } catch (Exception e) {
            logger.error(e.getClass().getName() + ";" + e.getMessage());
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> byte[] serializeList(List<T> list) {
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        Schema<T> schema = (Schema<T>) getSchema(list.get(0).getClass());
        LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ProtostuffIOUtil.writeListTo(byteArrayOutputStream, list, schema, buffer);
            byte[] result = byteArrayOutputStream.toByteArray();
            return result;
        } catch (Exception e) {
            logger.error(e.getClass().getName() + ";" + e.getMessage());
            throw new IllegalStateException(e.getMessage(), e);
        } finally {
            buffer.clear();
        }
    }

    public static <T> List<T> deserializeList(byte[] paramArrayOfByte, Class<T> clazz) {
        if (paramArrayOfByte == null || paramArrayOfByte.length == 0) {
            return null;
        }
        Schema<T> schema = getSchema(clazz);
        try {
            List<T> result = ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(paramArrayOfByte), schema);
            return result;
        } catch (IOException e) {
            logger.error(e.getClass().getName() + ";" + e.getMessage());
            throw new IllegalStateException(e.getMessage(), e);
        }
    }


}
